package com.roroldo.springcloud.controller;


import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.roroldo.springcloud.service.PaymentHystrixService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping(value = "/consumer/payment")
// 本类中服务调用出现问题，统一用 paymentGlobalFallbackMethod 方法处理
@DefaultProperties(defaultFallback = "paymentGlobalFallbackMethod")
public class OrderHystrixController {

    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id) {
        return paymentHystrixService.paymentInfo_OK(id);
    }

    @GetMapping("/hystrix/timeout/{id}")
    /*@HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="2000")
    })*/
    // 加了 @DefaultProperties 属性注解，如果没有写具体方法名字，就用统一全局的
    @HystrixCommand
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
        return paymentHystrixService.paymentInfo_TimeOut(id);
    }

    public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id) {
        return "我是消费者80，对方支付系统繁忙请10秒钟后再试或者自己运行出错，请检查自己,o(╥﹏╥)o";
    }

    // 统一服务降级处理方法
    public String paymentGlobalFallbackMethod() {
        return "Global 方法：对方繁忙或以及宕机，请稍后重试!";
    }

    @GetMapping("/hystrix/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfoHandlerException")
    public String paymentInfo(@PathVariable Integer id) throws IllegalAccessException {
        if (id < 0) {
            throw new IllegalAccessException("id 不能为负数");
        } else {
            return paymentHystrixService.paymentInfo_OK(id);
        }
    }

    // 服务降级处理方法的参数必须和服务方一致，如果是全局方法则不用
    public String paymentInfoHandlerException(Integer id) {
        return "服务支付接口调用异常！！！ ID 不能是负数";
    }
}
